//
//  FirstController.m
//  WalkiOS
//
//  Created by luqiuan on 2019/10/12.
//  Copyright © 2019 Chenmuzhou. All rights reserved.
//

#import "FirstController.h"
#import "WACycleScrollView.h"
#import "WACompleteProgressView.h"
#import "WAGetStepCount.h"
#import "WAMyTaskController.h"
#import "WNBusinessRequest.h"
#import "WACommentModel.h"
#import "WAMyTaskController.h"
#import "WACommentDetailController.h"
#import "WACommentListController.h"

static int numberOfStep = 0;

@interface FirstController ()


@property (nonatomic, strong) WACycleScrollView *operationView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityView;
@property (nonatomic, strong) WACompleteProgressView *completeProgressView;
@property (weak, nonatomic) IBOutlet UIView *imageContainView;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIView *commentContianView;
@property (weak, nonatomic) IBOutlet UIImageView *manImageView;
@property (weak, nonatomic) IBOutlet UIView *progressContainView;
@property (weak, nonatomic) IBOutlet UIButton *bottomBtn;

@property (weak, nonatomic) IBOutlet UILabel *activityLevelLB;
@property (weak, nonatomic) IBOutlet UILabel *userLevelLB;
@property (weak, nonatomic) IBOutlet UILabel *totalCandyNumberLB;

@property (weak, nonatomic) IBOutlet UILabel *commentLB;//公告

@property (nonatomic, strong) WAGetStepCount *getStepCount;

@property (nonatomic, strong) NSMutableArray *commentList;
@property (nonatomic, strong) NSTimer *commentTimer;
@property (nonatomic, assign) NSInteger commentPage;
@property (nonatomic, assign) BOOL loadComplete;
@property (nonatomic, assign) NSInteger currentCommentIndex;
@property (nonatomic, strong) WACommentModel *currentModel;
@end

@implementation FirstController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.commentLB.text = @"";
    self.bottomBtn.layer.cornerRadius = 23;
    self.bottomBtn.layer.masksToBounds = YES;
    self.bottomBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.bottomBtn.layer.borderWidth = 1.5;
    
    [self.imageContainView setNeedsLayout];
    [self.imageContainView layoutIfNeeded];
    [self.progressContainView setNeedsLayout];
    [self.progressContainView layoutIfNeeded];
    //轮播图
    self.operationView = [[WACycleScrollView alloc] initWithFrame:self.imageContainView.bounds];
    [self.imageContainView addSubview:self.operationView];
    [self.operationView configImages:nil];
    [self.operationView configImages:@[@"banner1",@"banner2",@"banner3",@"banner4"]];
    [self.operationView setClickItemBlock:^(NSInteger index) {
        
    }];
    @weakify(self)
    [self.operationView setDidScrollToIndexBlcok:^(NSInteger index) {
        @strongify(self)
        if (self.commentList.count > 0) {
            if (self.currentCommentIndex < self.commentList.count) {
                WACommentModel *model = self.commentList[self.currentCommentIndex];
                self.currentModel = model;
                self.commentLB.text = [model.content removeSpaceAndNewline];
                self.currentCommentIndex ++;
            }else{
                if (!self.loadComplete) {
                    [self loadModelComment];
                }
                self.currentCommentIndex = 0;
                WACommentModel *model = self.commentList[self.currentCommentIndex];
                self.currentModel = model;
                self.commentLB.text = [model.content removeSpaceAndNewline];
            }
        }
    }];
    //圈圈
    self.completeProgressView = [[WACompleteProgressView alloc] initWithFrame:self.progressContainView.bounds];
    [self.progressContainView addSubview:self.completeProgressView];
    
    self.getStepCount = [WAGetStepCount new];
    
    
    
    
    
    
    if ([self.loginManager isloginOnline]) {
        [self updateUserInfo];
        [self checkVision];
        [self reloadComment];
    }else{
        [self.loginManager presentLoginView:^(BOOL loginSuccess) {
            if (loginSuccess) {
                [self updateUserInfo];
                [self checkVision];
                [self reloadComment];
            }
        }];
    }
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentTapAction)];
    [self.commentContianView addGestureRecognizer:tapGes];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (![self.loginManager isloginOnline]) {
        [self.loginManager presentLoginView:^(BOOL loginSuccess) {
            if (loginSuccess) {
                [self updateUserInfo];
                [self checkVision];
                [self reloadComment];
            }
        }];
        return;
    }
    @weakify(self)
    [self.getStepCount getHealthDataWithBlock:^(BOOL success, NSInteger stepCount, CGFloat distances) {
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                @strongify(self)
                [self.completeProgressView configWith:4000 complete:stepCount];
                [self uploadStepCount:stepCount];
                [self.manImageView startAnimating];
            });
        }
    }];
    [self updateViews];
    [self.loginManager updateUserInfo:^(BOOL loginSuccess) {
        [self updateViews];
    }];

    self.manImageView.animationImages = @[[UIImage imageNamed:@"run1"],
    [UIImage imageNamed:@"run2"],
    [UIImage imageNamed:@"run3"]];
    self.manImageView.animationRepeatCount = 1;
    self.manImageView.animationDuration = 0.8;
    self.manImageView.image = [UIImage imageNamed:@"run1"];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)updateViews{
    WNUserInfo *info = self.loginManager.userInfo;
    self.activityLevelLB.text = info.activitylevel;
    self.userLevelLB.text = [NSString stringWithFormat:@"LV %@",info.viplevel];
    self.totalCandyNumberLB.text = [NSString stringWithFormat:@"%.1f",info.candynumber.floatValue];
    [self.bottomBtn setTitle:[NSString stringWithFormat:@"累计获得雨露:%.1f",info.totalcandynumber.floatValue] forState:0];
}

- (IBAction)rightBtnAction:(id)sender {
    WAMyTaskController *vc = [[WAMyTaskController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)updateUserInfo{
    NSString *ID = [@(self.loginManager.userInfo.userid) stringValue];
    [WNBusinessRequest getUserInfoWithID:ID Succ:^(id  _Nonnull responseObject) {
        
        self.loginManager.userInfo = [WNUserInfo yy_modelWithJSON:responseObject];
        [self.loginManager saveUserInfo];
        [self updateViews];
    } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
        
    }];
}

- (void)uploadStepCount:(NSInteger)count{
    if (count - numberOfStep < 100) {
        return;
    }
    numberOfStep = count;
    [WNBusinessRequest uploadStepCount:[@(count) stringValue] Succ:^(id  _Nonnull responseObject) {
        
    } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
        [WNTool show:mes];
    }];
}

- (void)getComment{
    [WNBusinessRequest getCommentInfoWithPageNum:self.commentPage Succ:^(id  _Nonnull responseObject) {
        [self.activityView stop];
        if (self.commentPage == 1) {
            self.commentList = [NSMutableArray new];
        }
        NSDictionary *dict = (NSDictionary *)responseObject;
        NSInteger total = [dict[@"total"] integerValue];
        NSArray *list = [WACommentModel mj_objectArrayWithKeyValuesArray:dict[@"data"]];
        [self.commentList addObjectsFromArray:list];
        if (self.commentList.count == total) {
            self.loadComplete = YES;
        }else{
            self.loadComplete = NO;
        }
        if (self.commentLB.text.length == 0) {
            self.currentModel = self.commentList.firstObject;
            self.commentLB.text = [self.currentModel.content removeSpaceAndNewline];
        }
    } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
        NSLog(@"");
        [self.activityView stop];
        [WNTool show:mes];
    }];
}

- (void)loadModelComment{
    self.commentPage++;
    [self getComment];
}

- (void)reloadComment{
    [self.activityView start];
    self.commentPage = 1;
    [self getComment];
}
  

- (void)checkVision{
    [WNBusinessRequest getNewVisionSucc:^(id  _Nonnull responseObject) {
            NSArray *list = (NSArray *)responseObject;
            NSDictionary *dict = list.firstObject;
            NSInteger res = [WNTool compareVersion2:[WNTool currentAppVersion] to:dict[@"versionno"]];
            if (res < 0) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"有新版本可以更新额" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.baby921.top/app/shareapp/share.html"]];
                }];
//                UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//                }];
                [alert addAction:action1];
//                [alert addAction:action2];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
            }
        } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
            
        }];
}

- (void)commentTapAction{
    WACommentListController *vc = [[WACommentListController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}
@end
